/*
 * Created by Huang 嵘才 on 18-2-7 上午11:22
 * Copyright (c) 2018. All rights reserved.
 * Last modified 18-2-6 下午4:17
 */

package io.esirong.image.fresco;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;

import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipelineConfig;

import io.esirong.image.ImageLoader;
import io.esirong.image.ImageLoaderOptions;
import io.esirong.image.ImageLoaderStrategy;

/**
 * FrescoImageLoader
 * Created by 黄嵘才(HuangRc) on 2018/2/1.
 */

public class FrescoImageLoader implements ImageLoaderStrategy {
    private static volatile FrescoImageLoader imageLoader;

    private FrescoImageLoader() {
    }

    /**
     * Get the singleton.
     *
     * @return the singleton
     */
    public static FrescoImageLoader get() {
        if (imageLoader == null) {
            synchronized (ImageLoader.class) {
                if (imageLoader == null) {
                    imageLoader = new FrescoImageLoader();
                }
            }
        }
        return imageLoader;
    }

    @Override
    public void init(Context appContext) {
        Fresco.initialize(appContext);
    }

    @Override
    public void showImage(View v, String url, final ImageLoaderOptions options) {
        if (v instanceof SimpleDraweeView) {
            SimpleDraweeView draweeView = (SimpleDraweeView) v;
            draweeView.setImageURI(url);
        }

    }

    @Override
    public void showImage(View v, int drawable, ImageLoaderOptions options) {
        if (v instanceof SimpleDraweeView) {
            SimpleDraweeView draweeView = (SimpleDraweeView) v;
            draweeView.setImageResource(drawable);
        }
    }

    @Override
    public void showImage(View v, byte[] imageBytes, ImageLoaderOptions options) {
        //TODO 委托fresco

    }


    public ImagePipelineConfig getPipelineConfig(Context context) {
        // set the cache file path
        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
                .setMaxCacheSize(30 * 1024 * 1024)
                .setMaxCacheSizeOnLowDiskSpace(5 * 1024 * 1024)
                .build();

        return ImagePipelineConfig.newBuilder(context)
                .setDownsampleEnabled(true)
                // 设置缓存
                .setMainDiskCacheConfig(diskCacheConfig)
                .setBitmapsConfig(Bitmap.Config.RGB_565)
                // 保证缓存达到一定条件就及时清除缓存
//                .setBitmapMemoryCacheParamsSupplier(new BitmapMemoryCacheParamsSupplier((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)))
                .build();
    }
}
